import BaseApi from "./BaseApi.js"
import baseRequest from "./BaseRquest.js"
import httpCode from '../config/HttpCode'

const GET = 'get';
const POST = 'post';
const PUT = 'put';
const DELETE = 'delete';


function request({
  url,
  data, //请求数据，object类型
  method = 'GET',
  isShowSysToast = true, //这个请求的方法是否显示后台的错误提示
  exceptCode = [], //哪些特殊状态码不会显示后台错误弹窗提示
  tip = '', //加载的loading提示，如果设置了则显示loading
  header = {
    'content-type': 'application/json' // 默认值
  },
}) {
  const app = getApp();
  const userInfoManager = app.userInfoManager;
  const mpAppInfo = app.mpAppInfo;
  if (tip) {
    wx.showLoading({
      title: tip,
    })
  }

  if (userInfoManager.isLogin()) {
    header['Authorization'] = mpAppInfo.getToken();
  }
  const config = {
    isShowSysToast: isShowSysToast,
    exceptCode: exceptCode,
  };
  url = BaseApi.getBaseUrl() + url;
  return baseRequest({
    url: url,
    data: data,
    method: method,
    header: header
  }).then(resolve => {
    config.response = resolve;
    wx.hideLoading();
    return doResolve(config);
  }).catch(rej => {
    config.error = rej;
    wx.hideLoading()
    if (config.response) {
      return Promise.reject(rej);
    }
    return doReject(config);
  })
}

function uploadFile({
  url,
  filePath,
  name = 'file',
  tip = '上传中，请稍后', //加载的loading提示，如果设置了则显示loading
  isShowSysToast = true, //这个请求的方法是否显示后台的错误提示
  exceptCode = [], //哪些特殊状态码不会显示后台错误弹窗提示
  otherFormData = {}, //除了文件外的其他表单文件
}) {
  const app = getApp();
  const userInfoManager = app.userInfoManager;
  const mpAppInfo = app.mpAppInfo;
  if (tip) {
    wx.showLoading({
      title: tip,
    })
  }
  const header = {
    'content-type': 'multipart/form-data' // 默认值
  };
  if (userInfoManager.isLogin()) {
    header['Authorization'] = mpAppInfo.getToken();
  }
  const config = {
    isShowSysToast: isShowSysToast,
    exceptCode: exceptCode,
  };
  url = BaseApi.getBaseUrl() + url;
  return new Promise((resolve, reject) => {
    console.log('上传文件的路径 ' + filePath);
    wx.uploadFile({
      url: url,
      filePath: filePath,
      name: name,
      formData: otherFormData,
      success(res) {
        console.debug('上传文件response：' + JSON.stringify(res))
        wx.hideLoading()
        if (!res.data) {
          Promise.reject(res);
          return;
        }
        config.response = res;
        try {
          config.response.data = JSON.parse(res.data)
        } catch (e) {
          Promise.reject(res);
        }
        resolve(doResolve(config))
      },
      fail(res) {
        config.error = rej;
        console.debug('上传文件失败：')
        wx.hideLoading()
        if (config.response) {
          Promise.reject(rej);
          return;
        }
        reject(doReject(config));
      },
      header: header
    })
  })

}

const doResolve = ({
  response = {},
  isShowSysToast = true,
  exceptCode = [],
  module = '',
  collectInfoPlusLogin = true
}) => {
  const app = getApp();
  const userInfoManager = app.userInfoManager;
  //数据全为空的情况
  if (!response) {
    if (isShowSysToast) {
      wx.showToast({
        duration: 1000,
        icon: 'none',
        title: '网络出错请重试'
      })
    }
    return Promise.reject(response);
  }
  if (response.status === 500){
    wx.showToast({
      duration: 1000,
      icon: 'none',
      title: '网络出错请重试'
    })
    return Promise.reject(response);
  }
  // console.log(JSON.stringify(response));
  //----------------------------
  //状态码非200的情况
  if (response.statusCode !== 200) {
    let errorMsg = '';
    //其他后续补充
    switch (response.statusCode) {
      // 404请求不存在
      case 404:
        errorMsg = '找不到页面啦';
        break;
        // 其他错误
      default:
        errorMsg = '网络出错请重试';
    }
    if (isShowSysToast) {
      wx.showToast({
        icon: 'none',
        duration: 1000,
        title: errorMsg
      })
    }
    return Promise.reject(response);
  }

  //----------------------------

  //返回的所有业务数据都是空的情况
  if (!response.data) {
    if (isShowSysToast) {
      wx.showToast({
        icon: 'none',
        duration: 1000,
        title: '找不到数据啦'
      })
    }
    return Promise.reject(response);
  }
  //----------------------------
  //到这里一般就是后台有返回数据了
  const realData = response.data;
  // console.log(realData.code, httpCode.HTTP_ERRORCODE_LOGIN_INVALID);
  if (realData.code === httpCode.HTTP_ERRORCODE_LOGIN_INVALID || realData.code === '41002' || realData.code === 41002) { //2 需要登录
    userInfoManager.clearUserInfo();
    var pages = getCurrentPages() //获取加载的页面
    var currentPage = pages[pages.length - 1] //获取当前页面的对象
    var url = currentPage.route //当前页面url

    console.log("当前路径 " + url);
    //防止重复跳转  
    if (url !== 'pages/login-process/login/login') {
      //到了这里说明是用户没有登录过，需要登录
      wx.reLaunch({
        url: '/pages/login-process/login/login',
        success: (result) => {

        },
        fail: () => {},
        complete: () => {}
      });
    }
  }
  return Promise.resolve(realData);
};

const doReject = ({
  isShowSysToast = true,
  error = {}
}) => {
  //处理非业务的错误
  if (isShowSysToast) {
    wx.showToast({
      icon: 'none',
      duration: 1000,
      title: '网络出错请重试',

    })
  }

  return Promise.reject(error)
};

export default {
  request,
  uploadFile,
  GET,
  PUT,
  POST,
  DELETE
}